yjx.controller('orderController', ['$rootScope', '$scope', '$stateParams', '$fetch', '$timeout', 'modalService', '$state', '$location', '$locals', 'wxShareService', 'ipCookie', function ($rootScope, $scope, $stateParams, $fetch, $timeout, modalService, $state, $location, $locals, wxShareService, ipCookie) {
    var productIds = $stateParams.productIds;
    $scope.forwardId = $stateParams.forwardId;
    var customerId = $stateParams.customerId;
    var productIdStr = '';//转发参数
    var isShopcart = false;
    var productIdArr = [], carItemIdArr = [];
    $scope.productList = [];
    $scope.client = {};//下单对象
    $scope.sampler = {};//采样送检对象
    $scope.reporter = {};//检测报告送检对象
    $scope.paying = false;
    $scope.agree = true;
    $scope.order = {
        totalPrice: 0,
        cTotalPrice: 0,//可使用优惠券的总金额
    };
    $scope.parent.discount = 0;
    $rootScope.user = $rootScope.user ? $rootScope.user : ipCookie('user');
    /*提交下单 检验数据合法性*/

    $scope.submit = function () {
        if (!$scope.client.id || !$scope.client.name || !$scope.client.telephone) {
            modalService.mainMsgError("请先选择客户");
            return;
        }
        if (!$scope.sampler.name) {
            modalService.mainMsgError("采样送检对象姓名不能为空");
            return;
        }
        if (!$scope.sampler.telephone) {
            modalService.mainMsgError("采样送检对象手机号不能为空");
            return;
        }
        if (!$scope.sampler.address) {
            modalService.mainMsgError("采样送检对象地址不能为空");
            return;
        }
        if (!$scope.reporter.name) {
            modalService.mainMsgError("检测报告寄送对象姓名不能为空");
            return;
        }
        if (!$scope.reporter.telephone) {
            modalService.mainMsgError("检测报告寄送对象手机号不能为空");
            return;
        }
        if (!$scope.reporter.address) {
            modalService.mainMsgError("检测报告寄送对象地址不能为空");
            return;
        }

        initParams();
    }

    function initParams() {
        $scope.paying = true;
        if (isShopcart) {
            for (var i = 0; i < $scope.productList.length; i++) {
                productIdArr.push($scope.productList[i].productId);
                carItemIdArr.push($scope.productList[i].carItemId);
            }
        }
        params = {
            productIds: productIdArr,
            orderType: $rootScope.identity == 1 ? false : true,
            interfaceMode: isShopcart ? false : true,
            samplingReceivePerson: $scope.sampler.name,
            samplingReceivePhone: $scope.sampler.telephone,
            samplingReceiveAddress: $scope.sampler.address,
            samplingReceiveMode: $rootScope.identity == 0 && !customerId ? 1 : $scope.samplerSwitch ? 1 : 0,
            reportReceivePerson: $scope.reporter.name,
            reportReceivePhone: $scope.reporter.telephone,
            reportReceiveAddress: $scope.reporter.address,
            reportReceiveMode: $rootScope.identity == 0 && !customerId ? 1 : $scope.reporterSwitch ? 1 : 0,//客户入口自行下单mode为1
        }
        if ($scope.forwardId > 0) {
            params.inviterUserId = $scope.forwardId;
        }
        if (isShopcart) {
            params.carItemIds = carItemIdArr;
        }
        if ($scope.parent.coupons.length > 0) {
            params.couponId = $scope.parent.coupons;
        }
        if (customerId && customerId > 0) {
            params.customerId = customerId
        } else if ($scope.client.id && $rootScope.identity == 1) {
            params.customerId = $scope.client.id;
        }
        getOrder();
    }
    /**下单 */
    function getOrder() {
        // alert("params.inviterUserId=="+params.inviterUserId);
        // alert("params.customerId=="+params.customerId);
        $fetch.fetch(
            '/unified/order',
            {
                params: params,
                type: 'get'
            }
        ).then(function (data) {
            $timeout(function () {
                // console.log(data);
                // if (params.totalPrice == 0) {
                //     //0元下单不调支付
                //         $scope.paying = false;
                //         $rootScope.from = "orderPay";
                //         $state.go('orderDetail', { id: data })
                //         modalService.mainMsgInfo("支付成功");
                // } else {
                getPrepay(data);
                // }

            })

        }).catch(function (e) {
            $scope.paying = false;
            if (e) {
                modalService.mainMsgError(e.msg)
            } else {
                modalService.mainMsgError("服务器出错")
            }

        })
    }
    /**微信支付 */
    function getPrepay(orderId) {
        var params = {
            orderId: orderId,
            // openid:$rootScope.user.openid,
        };
        //  alert(params.orderId+"===="+params.openid);
        $fetch.fetch(
            '/stayOrder/callPay',
            {
                params: params,
                type: 'get',
                cache: false,
            }
        ).then(function (data) {
            $timeout(function () {
                chooseWXPay(data, orderId);
            })
        }).catch(function (e) {
            $scope.paying = false;
            if (e) {
                modalService.mainMsgError(e.msg)
            } else {
                modalService.mainMsgError("服务器出错")
            }
        })
    }
    function chooseWXPay(data, orderId) {
        function onBridgeReady() {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": data.appId,     //公众号名称，由商户传入
                    "timeStamp": data.timeStamp,         //时间戳，自1970年以来的秒数
                    "nonceStr": data.nonceStr, //随机串
                    "package": data.package,
                    "signType": data.signType,         //微信签名方式：
                    "paySign": data.paySign //微信签名
                },
                function (res) {
                    //alert(res.err_msg)
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        //alert(res.err_msg)
                        $timeout(function () {
                            $scope.paying = false;
                            $rootScope.from = "orderPay";
                            $state.go('orderDetail', { id: orderId })
                            modalService.mainMsgInfo("支付成功");
                        })
                    }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                    else {
                        $scope.paying = false;
                    }
                }
            );
        }
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
            modalService.mainMsgInfo("请先关注基因团公众号<br>并在微信浏览器在中完成支付")
        } else {
            onBridgeReady();
        }
    }
    /**获取用户基础信息 */
    function getInfo(id) {
        $fetch.fetch(
            '/userInfo/getById',
            { params: { userId: id } }
        ).then(function (data) {
            $timeout(function () {
                $scope.forward = {
                    id: data.user.id,
                    name: data.user.realname ? data.user.realname : data.user.nickname,
                    telephone: data.user.telephone,
                    address: data.user.address,
                }
            })
        }).catch(function (e) {
            modalService.mainMsgError(e.msg);
        })
    }

    /**获取产品基础信息 */
    function getProduct(id) {
        $fetch.fetch(
            '/product/getSimpleDetail',
            {
                params: { productId: id }
            }
        ).then(function (data) {
            $scope.productList.push(data);
            var price = data.price ? data.price : data.originalPrice;
            $scope.order.totalPrice = $scope.order.totalPrice + price;
            if (data.useCouponState) {
                $scope.order.cTotalPrice = $scope.order.cTotalPrice + price;
            }
        })
    }

    /**开关 */
    $scope.samplerSwitchFuc = function () {
        $scope.samplerSwitch = !$scope.samplerSwitch;
        if ($scope.samplerSwitch) {
            $scope.sampler = { name: $scope.forward.name, telephone: $scope.forward.telephone, address: $scope.forward.address };
        } else {
            $scope.sampler = $scope.client;
        }
    }
    $scope.reportSwitchFuc = function () {
        $scope.reporterSwitch = !$scope.reporterSwitch;
        if ($scope.reporterSwitch) {
            $scope.reporter = { name: $scope.forward.name, telephone: $scope.forward.telephone, address: $scope.forward.address };
        } else {
            $scope.reporter = $scope.client;
        }
    }
    /**健康管家信息 */
    if ($scope.forwardId) {
        getInfo($scope.forwardId);
    } else {
        $scope.forward = {
            id: $rootScope.user.id,
            name: $rootScope.user.realname ? $rootScope.user.realname : $rootScope.user.nickname,
            telephone: $rootScope.user.telephone,
            address: $rootScope.user.address,
        }
    }

    /**当用户为客户时 初始化client信息 */
    if ($rootScope.identity == 0) {
        $timeout(function () {
            $scope.client = {
                id: $rootScope.user.id,
                name: $rootScope.user.nickname,
                telephone: $rootScope.user.telephone,
                address: $rootScope.user.address
            };
            $scope.sampler = {
                id: $rootScope.user.id,
                name: $rootScope.user.nickname,
                telephone: $rootScope.user.telephone,
                address: $rootScope.user.address
            };
            $scope.reporter = {
                id: $rootScope.user.id,
                name: $rootScope.user.nickname,
                telephone: $rootScope.user.telephone,
                address: $rootScope.user.address
            };
        })
    }
    /**订单 产品信息 */
    if (productIds) {
        /**来自转发链接或详情页直接下单 */
        productIdStr = productIds;
        productIdArr = productIds.split(',')
        // console.log("非购物车来源:================");
        // console.log(productIdArr)
        for (var i = 0; i < productIdArr.length; i++) {
            getProduct(productIdArr[i]);
        }
    } else {
        /**来自购物车 */
        isShopcart = true;
        $scope.productList = $scope.$parent.orderList;
        $scope.order = $scope.obj;
    }
    /**禁止产品跳转 */
    $scope.onClick = function ($event) {
        $event.preventDefault();
    }
    /**选择客户 */
    $scope.clientSelect = function (item) {
        item.isCheck = !item.isCheck;
        $scope.client = item;
        $scope.sampler = { name: item.name, telephone: item.telephone, address: item.address };
        $scope.reporter = item;
        $scope.samplerSwitch = false;
        $scope.reporterSwitch = false;
        history.back();
    }
    /**获取客户列表 */
    function getClientList() {
        $fetch.fetch(
            '/customer/list',
            {
                params: {
                    // userId: $rootScope.userId
                },
                cache: false
            }
        ).then(function (data) {
            $timeout(function () {
                $scope.clientList = data;
            })
        }).catch(function (e) {
            modalService.mainMsgError(e.msg)
        })
    }
    if ($rootScope.userId) {
        getClientList();
        getCoupons();
    }
    /**获取优惠券列表 */
    function getCoupons() {
        $fetch.fetch(
            '/user/coupon/me',
            {
                cache: false
            }
        ).then(function (data) {
            $timeout(function () {
                $scope.parent.couponList = data;
            })
        })
    }
    /**选择优惠券 */
    $scope.checkIt = function (item) {
        var checkNow = !item.isCheck;
        for (var i = 0; i < $scope.parent.couponList.length; i++) {
            $scope.parent.couponList[i].isCheck = false;
        }
        var value = item.deductibleMax > 0 ? item.deductibleMax / 100 * $scope.order.cTotalPrice > item.value ? item.value : item.deductibleMax / 100 * $scope.order.cTotalPrice : item.value;
        // if (item.condition <= $scope.order.totalPrice) {现在优惠券没有使用条件
        item.isCheck = checkNow;
        if (item.isCheck) {
            $scope.parent.coupons = [item.userCouponId];
            $scope.parent.discount = value;
            // $scope.order.totalPrice = $scope.order.totalPrice - value;
        } else {
            $scope.parent.coupons = [];
            $scope.parent.discount = 0;
            // $scope.order.totalPrice = $scope.order.totalPrice + value;
        }
        // } else {
        //     return;
        // }
    }
    $scope.couponSelect = function () {
        history.back();
    }
    /**发送客户下单 */
    $scope.forwardReady = function () {
        if (!$scope.client.id) {
            modalService.mainMsgInfo("请选择要转发的客户");
            return;
        }
        if (isShopcart) {
            for (var i = 0; i < $scope.productList.length; i++) {
                productIdArr.push($scope.productList[i].productId);
            }
            productIdStr = productIdArr.join(',');
        }

        // if ($scope.isAndroid) {
        //     $scope.link = APPSRC + "?url=shopcart/order&productIds=" + productIdStr + "&forwardId=" + $rootScope.userId+ "&customerId=" + $scope.client.id;
        // } else {
        //     $scope.link = APPSRC + '#/' + "shopcart/order?productIds=" + productIdStr + "&forwardId=" + $rootScope.userId+ "&customerId=" + $scope.client.id;
        // }
        $scope.link = APPSRC + '#/' + "shopcart/order?productIds=" + productIdStr + "&forwardId=" + $rootScope.userId + "&customerId=" + $scope.client.id;

        wxShareService.onHideMenuItems();
        wxShareService.onMenuShareAppMessage('', '', '', $scope.link, '')
        modalService.mainMsgInfo("点击右上角发送给客户下单")
    }
}])